package com.cyh;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

public class MyUnsafe {
    public static void main(String[] args) {
        try {
            Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
            theUnsafe.setAccessible(true); //可以访问私有
            Unsafe unsafe = (Unsafe)theUnsafe.get(null);

            System.out.println(unsafe);

            //获取域的偏移地址
            long idOffset = unsafe.objectFieldOffset(Teacher.class.getDeclaredField("id"));
            long nameOffset = unsafe.objectFieldOffset(Teacher.class.getDeclaredField("name"));

            Teacher t = new Teacher();

            //对属性的值进行修改
            unsafe.compareAndSwapInt(t, idOffset, 0, 1); //从原0值变成新1值
            unsafe.compareAndSwapObject(t, nameOffset, null, "张三");//从原null变成新字符串

            System.out.println(t);

        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

class Teacher{
    volatile int id;
    volatile String name;

    @Override
    public String toString() {
        return "Teacher{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}
